﻿using DFGK_WMS.IRepository.IService;
using DFGK_WMS.Model.Models;
using DFGK_WMS.Repository.Service;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace DFGK_WMS.WebAPI.Controllers.Material
{
    [Route("api/[controller]")]
    [ApiController]
    public class MaterialController : ControllerBase
    {

        private readonly IMaterialService materialService;

        private readonly ISqlSugarClient _Client;

        public MaterialController(IMaterialService materialService, ISqlSugarClient client)
        {
            this.materialService = materialService;
            _Client = client;
        }

        /// <summary>
        /// 获取物料菜单递归列表
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetAllMaterialType")]
        public IActionResult GetAllMaterialType(string? name)
        {
            var result = materialService.GetMaterialType(name);

            return new JsonResult(result);
        }    




        /// <summary>
        /// 获取物料列表（分页查询）
        /// </summary>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">页容量</param>
        /// <param name="code">物料编码</param>
        /// <param name="name">物料名称</param>
        /// <param name="materTypeId">物料类型id</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetMaterialList/{pageIndex}/{pageSize}")]
        public IActionResult GetMaterialList(int pageIndex, int pageSize, string? code, string? name, int? materTypeId)
        {
            var result = materialService.GetMaterialList(pageIndex, pageSize, code, name, materTypeId);

            return new JsonResult(result);
        }


        [HttpGet]
        [Route("UpdateMaterialNode")]
        public IActionResult UpdateMaterialNode(  )
        {
            var list = _Client.Queryable<TMaterialCategory>().AS("TMaterialCategories").ToList();


            foreach (var item in list)
            {
                bool isLeaf = false;
                if (!list.Any(t => t.ParentId == item.Id))
                {
                    isLeaf = true;
                }
                item.IsLeaf = isLeaf;

                bool result = _Client.Updateable<TMaterialCategory>(item).AS("TMaterialCategories").WhereColumns("Id").ExecuteCommand()>0;

                Console.WriteLine("result:" + result);  
            }

            return new JsonResult("");

        }
    }
}
